<?php
// +----------------------------------------------------------------------
// | Copyright © Sogu Technologies Co. Ltd 2018-2050 All rights reserved.
// +----------------------------------------------------------------------
// | File name: UserInfoController.php
// +----------------------------------------------------------------------
// | Author: liuju
// +----------------------------------------------------------------------
// | Description:  提供App端用户信息处理功能
// +----------------------------------------------------------------------
// | Others: 其他内容的说明
// +----------------------------------------------------------------------
// | History: 修改历史记录列表，每条修改记录应包含修改日期、修改者及修改内容简述
// +----------------------------------------------------------------------
// | 1.Date: 2018-12-27 Author: liuju Modification: 创建
// +----------------------------------------------------------------------

namespace App\Http\Controllers\Frontend\V10\Users;

use App\Constant\SmsTemplate;
use App\Facades\CommonPlatformRequestFacade;
use App\Http\Controllers\Controller;
use App\Http\Requests\Frontend\V10\Common\AvatarRequest;
use App\Http\Requests\Frontend\V10\Users\CertNumRequest;
use App\Http\Requests\Frontend\V10\Users\ModifyPassRequest;
use App\Http\Requests\Frontend\V10\Users\VerifyImageCodeRequest;
use App\Http\Requests\Frontend\V10\Users\VerifyPhoneRequest;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
use Symfony\Component\HttpFoundation\Response;
use Tymon\JWTAuth\Facades\JWTAuth;

class UserController extends Controller
{


    /**
     * 当前用户
     * @var
     */
    protected $user;

    public function __construct(Request $request)
    {
        $this->middleware('auth:api')->only([
            'me',
            'uploadAvatar',
            'modifyPassword',
        ]);
        $this->user = auth('api')->user();
    }


    /**
     * Description: 获取当前用户信息
     * Author: liuju
     * DateTime: 2018-12-27 13:50
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        return respond(['user' => User::getCurrentUserDetailByApp($this->user)]);
    }


    /**
     * Description: 验证图形验证码
     * Author: liuju
     * DateTime: 2019-03-09 15:36
     * @param VerifyImageCodeRequest $request
     * @return mixed
     */
    public function  verifyImageCode(VerifyImageCodeRequest $request)
    {
        if (!captcha_api_check($request->get('captcha'), $request->get('key'))) {
            return respond([], '图形验证码不正确',Response::HTTP_BAD_REQUEST);
        }
        return success([],[],'验证成功');
    }





    /**
     * Description: 用户修改密码前发送验证码，确认当前用户是否为账号手机注册用户
     * Author: liuju
     * DateTime: 2018-12-27 15:43
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function smsUser(Request $request,$phoneNum)
    {
        if (!User::where('phone_num', $phoneNum)->value('id')) {
            return failed('该用户不存在');
        }
        $key1 = 'sms_user_modify_pass_'.$phoneNum;
        //如果该IP下该账号该申请验证码操作一分钟内已提交，提示用户不要重复请求
        if (Cache::get($key1)) {
            return respond([], '验证码已生成，请勿重复操作', Response::HTTP_EXPECTATION_FAILED);
        }
        $code = mt_rand(100000, 999999);
        //请求第三方短信发送接口
        $templateId = SmsTemplate::TEMPLATE_RESET;
        if(auth('api')->user()){
            $templateId = SmsTemplate::TEMPLATE_MODIFY_PASS;
        }
        $res = CommonPlatformRequestFacade::sms($phoneNum, $templateId,['validCode' => strval($code)]);
        if ($res['code'] !== '01') {
            return respond([], '验证码生成错误'.$res['message'], Response::HTTP_INTERNAL_SERVER_ERROR);
        }
        Cache::add($key1,time(),1);
        $key2 = 'sms_verify_phone_' . $phoneNum . $request->getClientIp();
        Cache::add($key2, $code, 10);
        return respond([], '验证码已生成', Response::HTTP_OK);
    }


    public function getCaptcha()
    {
        $captcha = app('captcha')->create('default', true);
        unset($captcha['sensitive']);
        return respond($captcha);
    }

    /**
     * Description:  验证用户填写验证码是否正确
     * Author: liuju
     * DateTime: 2018-12-27 18:33
     * @param VerifyPhoneRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verifySms(VerifyPhoneRequest $request)
    {
        $phoneNum = $request->get('phone_num');
        if (!$user =User::where('phone_num', $phoneNum)->first()) {
            return failed('该用户不存在');
        }
        $key = 'sms_verify_phone_' . $phoneNum . $request->getClientIp();
        if ($user->phone_num != $phoneNum) {
            Cache::forget($key);
            return respond([], '',Response::HTTP_BAD_REQUEST);
        }
        if (!captcha_api_check($request->get('captcha'), $request->get('key'))) {
            Cache::forget($key);
            return respond([], '验证码不正确，请重新输入',Response::HTTP_BAD_REQUEST);
        }
        $code = Cache::get($key);
        if (!$code || $request->get('sms_code') != $code) {
            Cache::forget($key);
            return respond([], '短信验证码不正确，请重新输入',Response::HTTP_BAD_REQUEST);
        }
        //删除验证码缓存
        Cache::forget($key);
        //记录用户已经完成手机号码验证操作
        Cache::add('sms_verify_phone_action_' . $phoneNum . $request->getClientIp(), time(), 60);
        //用户是否实名验证，验证过跳转身份证号码验证页，其他直接修改密码
        $data = ['is_ocr' => false];
        if ($userCert = $user->valid) {
            $data['real_name'] = $userCert->name;
            $data ['is_ocr'] = true;
        }
        return respond($data, '验证成功', Response::HTTP_OK);
    }


    /**
     * Description: 用户身份证验证
     * Author: liuju
     * DateTime: 2018-12-28 15:32
     * @param CertNumRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function verifyCert(CertNumRequest $request)
    {
        $phoneNum = $request->get('phone_num');
        $user = User::where('phone_num', $phoneNum)->first();
        if (!$user) {
            return failed('该用户不存在');
        }
        $key = 'sms_verify_phone_action_' . $phoneNum . $request->getClientIp();
        if (!Cache::get($key)) {
            return respond([], '验证失败', Response::HTTP_BAD_REQUEST);
        }

        $certInfo = $user->valid;
        if (!$certInfo) {
            return failed('该用户尚未实名认证');
        }
        if($certInfo->name != $request->get('name')){
            return respond([],'身份证姓名验证失败',Response::HTTP_BAD_REQUEST);
        }
        if ($certInfo->num != $request->get('cert_num')) {
            return respond([], '身份证账号验证失败', Response::HTTP_BAD_REQUEST);
        }
        Cache::add('cert_verify_' . $user->id, time(), 60);
        return respond([], '验证成功', Response::HTTP_OK);

    }


    /**
     * Description:
     * Author: liuju
     * DateTime: 2018-12-28 17:51
     * @param ModifyPassRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function modifyPass(ModifyPassRequest $request)
    {
        $phoneNum = $request->get('phone_num');
        $user = User::where('phone_num', $phoneNum)->first();
        if (!$user) {
            return failed('该用户不存在');
        }
        $key1 = 'sms_verify_phone_action_' . $phoneNum . $request->getClientIp();
        if (!Cache::get($key1)) {
            return respond([], '请求失败', Response::HTTP_BAD_REQUEST);
        }
        $certInfo = $user->valid;
        $key2 = 'cert_verify_' . $user->id;
        $certVerify = Cache::get($key2);
        if ($certInfo && !$certVerify) {
            return respond([], '请求失败', Response::HTTP_BAD_REQUEST);
        }
        $user->password = $request->get('n_password');
        if (!$user->save()) {
            return respond([], '修改密码操作失败');
        }
        Cache::forget($key1);
        Cache::forget($key2);
        return success([]);
    }


    /**
     * Description: 用户上传头像
     * Author: liuju
     * DateTime: 2018-12-29 15:19
     * @param AvatarRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function uploadAvatar(AvatarRequest $request)
    {
        $userId = auth('api')->user()->id;
        $fileSize = $request->file('avatar')->getSize();
        if ($fileSize > 300 * 1024) {
            return respond([], '用户头像大小超过300KB', Response::HTTP_BAD_REQUEST);
        }
        try {
            $path = Storage::disk('oss')->putFile('avatar/frontend/'.date('YmdHis') . md5('user_avatar_' . $userId), $request->file('avatar'));
        } catch (\Exception $e) {
            return failed($e->getMessage());
        }
        $user = auth('api')->user();
        $user->avatar = $path;
        $user->save();
        return respond([
            'new_avatar' => $user->avatarShow,
        ], '上传成功');
    }

    /**
     * Description:在线改密码
     * Author: liuju
     * DateTime: 2019-01-05 22:39
     * @param ModifyPassRequest $request
     * @return mixed
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function modifyPassword(ModifyPassRequest $request)
    {
        $oldPass = $request->get('old_password');
        $user = auth('api')->user();

        $checkPass = Hash::check($oldPass,$user->password);
        //兼容larave自带密码加密和旧卡贷sha512加密
        if($checkPass || hash_equals($user->password,hash('sha512',$oldPass))){
            $user->password= $request->get('n_password');
            $user->save();
            JWTAuth::parseToken()->invalidate();
            return success([],[],'操作成功');
        }else{
            return failed('旧密码错误');
        }
    }

    /**
     * Description: 临时修改密码
     * Author: liChunlong
     * DateTime: 2019-04-15
     * @param ModifyPassRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \Tymon\JWTAuth\Exceptions\JWTException
     */
    public function tempTestModifyPass(ModifyPassRequest $request)
    {
        $phoneNum = $request->get('phone_num');
        $user = User::where('phone_num', $phoneNum)->first();
        if (!$user) {
            return failed('该用户不存在');
        }
        /*
        $key1 = 'sms_verify_phone_action_' . $phoneNum . $request->getClientIp();
        if (!Cache::get($key1)) {
            return respond([], '请求失败', Response::HTTP_BAD_REQUEST);
        }
        $certInfo = $user->valid;
        $key2 = 'cert_verify_' . $user->id;
        $certVerify = Cache::get($key2);
        if ($certInfo && !$certVerify) {
            return respond([], '请求失败', Response::HTTP_BAD_REQUEST);
        }
        */
        $user->password = $request->get('n_password');
        if (!$user->save()) {
            return respond([], '修改密码操作失败');
        }
        dd($user);
//        Cache::forget($key1);
//        Cache::forget($key2);
        return success([]);
    }

}

